// import 'dart:ffi';

import 'dart:async';
import 'dart:ffi';

import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
// import 'package:flutter/widgets.dart';
// import 'package:path_provider/path_provider.dart';
import 'package:flutter/services.dart';
import 'dart:convert';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:provider/provider.dart';
import 'package:heven/state/music.dart';

class MusicPlayer extends StatefulWidget {
  const MusicPlayer({super.key});

  @override
  _MusicPlayerState createState() => _MusicPlayerState();
}

class _MusicPlayerState extends State<MusicPlayer> {
 
  final AudioPlayer audioPlayer = AudioPlayer();
  bool isPlaying = false;
  bool _isAnimating = false;
  bool _isPlayProgress = false;
  Duration duration = Duration.zero;
  Duration position = Duration.zero;
  double progress = 0.0;
  List<String> songs = [
    'sounds/bysh.mp3',
    'sounds/pm.mp3',
    'sounds/bysh.mp3',
    'sounds/pm.mp3',
  ];
  int currentSongIndex = 0;
  List<LyricLine> lyrics = [];
  int currentLyricIndex = 0;
  final ScrollController _scrollController = ScrollController();
  // final _positionChangedDebounce = Debounce(timeout: Duration(milliseconds: 50));

  @override
  void initState() {
    super.initState();
    _isPlayProgress = true;
    audioPlayer.setReleaseMode(ReleaseMode.stop);

    loadLyrics();
    // 监听音频状态变化
    audioPlayer.onDurationChanged.listen((d) {
      setState(() {
        duration = d;
      });
    });
    // 监听音频位置变化
    audioPlayer.onPositionChanged.listen((pos) {
      // _positionChangedDebounce.call(() {
      // 这里的函数体不需要参数，所以直接使用
      if (_isPlayProgress) {
        setState(() {
          position = pos;
          progress = (pos.inMilliseconds.toDouble() / duration.inMilliseconds)
              .clamp(0.0, 1.0);

          if (findMatchingLyricIndex(pos) != currentLyricIndex) {
            currentLyricIndex = findMatchingLyricIndex(pos);
            _updateCurrentLyricIndex(currentLyricIndex);
          }
        });
      }
    });
// });
    _scrollController.addListener(() {
      if (_scrollController.offset !=
          _scrollController.position.maxScrollExtent) {
        // 用户正在滚动，取消任何可能的动画
        _isAnimating = false;
      }
    });

    audioPlayer.play(AssetSource(songs[currentSongIndex]) as Source);

    Timer(const Duration(milliseconds: 500), () {
      playAudio();
    });
  }

  @override
  void dispose() {
    _isPlayProgress = false;
    audioPlayer.stop();
    audioPlayer.release();
    _scrollController.dispose();
    super.dispose();
  }

  void _updateCurrentLyricIndex(newIndex) {
    // Calculate the pixel offset based on the new index
    final double pixelsPerLine =
        _scrollController.position.maxScrollExtent / lyrics.length;
    final double targetOffset = pixelsPerLine * newIndex;

    // 只有在没有动画进行，并且不在边缘时才进行动画
    if (!_isAnimating && !_scrollController.position.atEdge) {
      _scrollController
          .animateTo(
        targetOffset,
        duration: Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      )
          .whenComplete(() {
        _isAnimating = false;
      });
      _isAnimating = true;
    }
  }

  void delayedAction() async {
    await Future.delayed(const Duration(seconds: 1));
    playAudio();
    print('This message will be printed after 2 seconds.');
  }

  playAudio() async {
    await audioPlayer.play(AssetSource(songs[currentSongIndex]) as Source);
    setState(() {
      isPlaying = true;
    });
  }

  pauseAudio() async {
    await audioPlayer.pause();
    setState(() {
      isPlaying = false;
    });
  }

  nextSong() {
    setState(() {
      currentSongIndex = (currentSongIndex + 1) % songs.length;
      isPlaying = false;
      progress = 0.0;
      loadLyrics();
      _scrollController.jumpTo(0.0);
      playAudio();
    });
  }

  previousSong() {
    setState(() {
      currentSongIndex =
          (currentSongIndex == 0) ? songs.length - 1 : currentSongIndex - 1;
      isPlaying = false;
      progress = 0.0;
      loadLyrics();
      _scrollController.jumpTo(0.0);
      playAudio();
    });
  }

  seekToPosition(Duration newPos) async {
    await audioPlayer.seek(newPos);
  }

  loadLyrics() async {
    final String lyricsContent = await loadLyricsFromFile(
        'assets/lyrics/${songs[currentSongIndex].split('/').last.split('.').first}.lrc');
    lyrics = parseLyrics(lyricsContent);
  }

  //注释的不知道为什么找不到文件
  Future<String> loadLyricsFromFile(String path) async {
    try {
      final bytes = await rootBundle.load(path);
      final content = utf8.decode(bytes.buffer.asUint8List());

      return content;
    } catch (e) {
      print('Exception when trying to load lyrics from assets: $e');
      throw e;
    }
   
  }

  List<LyricLine> parseLyrics(String lyricsContent) {
    final List<LyricLine> lines = [];
    final regex = RegExp(r'\[(\d{2}):(\d{2})\.(\d{2})\](.*)');
    final allLines = lyricsContent.split('\n');

    for (final line in allLines) {
      final match = regex.firstMatch(line);
      if (match != null) {
        final minutes = int.parse(match.group(1) ?? '0');
        final seconds = int.parse(match.group(2) ?? '0');
        final milliseconds = int.parse(match.group(3) ?? '0') * 10;
        final time = Duration(
            minutes: minutes, seconds: seconds, milliseconds: milliseconds);
        final text = match.group(4) ?? '0';

        lines.add(LyricLine(time, text));
      }
    }

    return lines;
  }

  int findMatchingLyricIndex(Duration position) {
    int low = 0;
    int high = lyrics.length - 1;
    while (low <= high) {
      final mid = (low + high) ~/ 2;
      if (position >= lyrics[mid].time) {
        if (mid + 1 < lyrics.length && position < lyrics[mid + 1].time) {
          return mid;
        }
        low = mid + 1;
      } else {
        high = mid - 1;
      }
    }
    return -1;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomLeft,
          colors: <Color>[
            Color(0xFF060606),
            Color(0xFF145221),
          ],
        ),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10.0), // 设置圆角半径
            ),
            padding: const EdgeInsets.fromLTRB(44, 10, 44, 15), // 添加边距
            child: ClipRRect(
              borderRadius: BorderRadius.circular(10.0), // 圆角与Container保持一致
              child: CachedNetworkImage(
                imageUrl:
                    'https://img.fjshihui.com/e4675e70-549a-493a-be37-7924ae4acbd6.jpg',
                placeholder: (context, url) => CircularProgressIndicator(),
                errorWidget: (context, url, error) => Icon(Icons.error),
              ),
            ),
          ),
          const Padding(
            padding: EdgeInsets.only(left: 19, right: 19),
            child: Text(
              '不要说话',
              style: TextStyle(color: Colors.white, fontSize: 17, height: 1.5),
            ),
          ),
          Slider(
            value: progress,
            min: 0,
            max: 1,
            activeColor: Colors.white,
            inactiveColor: const Color(0xFFA1A1A1),
            onChanged: (double newProgress) {
              final clampedProgress = newProgress.clamp(0.0, 1.0);
              final newPos = Duration(
                  milliseconds:
                      (clampedProgress * duration.inMilliseconds).toInt());
              seekToPosition(newPos);
              setState(() {
                progress = clampedProgress;
              });
            },
          ),
          Padding(
              padding: const EdgeInsets.only(left: 19, right: 19),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '${position.inMinutes}:${(position.inSeconds % 60).toString().padLeft(2, '0')} ',
                    // style: Theme.of(context).textTheme.bodyMedium ,
                    style: const TextStyle(
                      color: Color(0xFFFFFFFF),
                      fontSize: 11,
                      height: 1.3,
                    ),
                  ),
                  Text(
                    '${duration.inMinutes}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}',
                    // style: Theme.of(context).textTheme.bodyMedium ,
                    style: const TextStyle(
                      color: Color(0xFFFFFFFF),
                      fontSize: 11,
                      height: 1.3,
                    ),
                  ),
                ],
              )),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              GestureDetector(
                onTap: previousSong,
                child: Image.asset(
                  'assets/images/last.png',
                  width: 29,
                  height: 25,
                ),
              ),
              const SizedBox(width: 37.5),
              GestureDetector(
                onTap: isPlaying ? pauseAudio : playAudio,
                child: Image.asset(
                  isPlaying
                      ? 'assets/images/stop.png'
                      : 'assets/images/play.png',
                  width: 55,
                  height: 55,
                ),
              ),
              const SizedBox(width: 37.5),
              GestureDetector(
                onTap: nextSong,
                child: Image.asset(
                  'assets/images/next.png',
                  width: 29,
                  height: 25,
                ),
              ),
            ],
          ),
          Expanded(
              child: Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10.0), // 设置圆角半径
                    color: const Color(0xFF323851),
                  ),
                  margin: const EdgeInsets.fromLTRB(22, 40, 22, 10),
                  child: Column(children: [
                    const ListTile(
                        title: Text(
                      '歌词',
                      style: TextStyle(
                          color: Color(0xFF00E8C6), fontSize: 14, height: 1.5),
                    )),
                    Expanded(
                      child: ListView.builder(
                        controller: _scrollController,
                        itemCount: lyrics.length,
                        padding: const EdgeInsets.all(15),
                        itemBuilder: (context, index) {
                          final line = lyrics[index];
                          return Text(
                            line.text,
                            style: TextStyle(
                                color: index == currentLyricIndex
                                    ? const Color(0xFF00E8C6)
                                    : Colors.white,
                                fontSize: 14,
                                height: 1.5),
                          );
                        },
                      ),
                    )
                  ]))),
        ],
      ),
    );
  }
}

class LyricLine {
  final Duration time;
  final String text;

  LyricLine(this.time, this.text);
}

